const resOss = {"msg":"请求成功","code":200,"data":{"AccessKeyId":"STS.NUQNeBUVvv1h1N9fM4RH1WYQR","AccessKeySecret":"5TMCy1XZiCCU6pmeHhNbSsnhTgEpqhqNCjXhnHCnQZcL","SecurityToken":"CAISlgJ1q6Ft5B2yfSjIr5bkBd/2uIlXwfODM2iIgk1hXscduJz6sDz2IHhEf3ZpAuwWsf00nGpS7/oblol/EMVIHhyeNZAotc9Z+lP4PtWb65fsveNeg5SrRWHMV0Z1WCt8oqOrIunGc9KBNnr29EYqs4aYGBymW1u6S+rr7bdsctUQWCShcDNCH604DwB+qcgcRxSzWPG2KUyo+CmyanBloQ1hk2hyxL2iy8mHkHrkgUb91/UeqvaWQP2tZNI+O4xkAZXnnr40VNKYj3UItUcVqvYt0vMVpW+dhLzHXQkNuSfhGvHP79hiIDV+YqUHAKNepJD+76Yg6reMzt+rm0kUZrkPCX2DHZrPx9DfXfi1Lcb7k0J6/90suRqAAVV6PwXJmz1jKuBDRSnuIAcxQ9dWcwluz+ZZKvbz/57mShXBaUwlj95pA55goG10EdJTm3Q6XZRoZWfs/iY1AH8VfMUeD/poCnhUumziVHJD/rypaK2QiGvC2uzALlEw43MnaVqNjX0U0Tpdkl/VlI0FWBsWGVmphUIkqOiWTiNz","expiration":"2020-06-09 11:07:09","tmpSecretId":null,"tmpSecretKey":null,"sessionToken":null,"expiredTime":null,"beginTime":null},"tid":"b4d8a488-8c15-4531-91fa-1a0f5cb0bbe9"}
let credentials = null; // STS凭证
let ossClient = null; // oss客户端实例
let fileInput = document.getElementById('fileInput'); // 文件选择器
let status = document.getElementById('status'); // 状态显示元素
const bucket = 'tororo-service'; // bucket名称
const region = 'oss-cn-beijing'; // oss服务区域名称
const partSize = 1024 * 1024; // 每个分片大小(byte)1024 * 1024
const parallel = 3; // 同时上传的分片数
const checkpoints = {}; // 所有分片上传文件的检查点
   window.onload = function(){
    credentials = null; // STS凭证
    ossClient = null; // oss客户端实例
    fileInput = document.getElementById('fileInput'); // 文件选择器
    status = document.getElementById('status'); // 状态显示元素
   }

    // 获取STS Token
function getCredential() {
  return fetch('http://192.168.1.164:3000/oss-token')
    .then(res => {
      return res.json()
    })
    .then(res => {
        console.log()
      credentials = res.data;
    })
    .catch(err => {
      console.error(err);
      credentials = resOss.data
      
    });
}

// 创建OSS Client
async function initOSSClient() {
  const { AccessKeyId, AccessKeySecret, SecurityToken } = credentials;
  ossClient = new OSS({
    secure:true,
    accessKeyId: AccessKeyId,
    accessKeySecret: AccessKeySecret,
    stsToken: SecurityToken,
    bucket,
    region
  });
}

async function upload() {
  status.innerText = 'Uploading';
  // 获取STS Token
  await getCredential();
  const { files } = fileInput;
  const fileList = Array.from(files);
  const uploadTasks = fileList.forEach(file => {
    // 如果文件大学小于分片大小，使用普通上传，否则使用分片上传
    if (file.size < partSize) {
      commonUpload(file);
    } else {
      multipartUpload(file);
    }
  });
}

// 普通上传
async function commonUpload(file) {
  if (!ossClient) {
    await initOSSClient();
  }
  const fileName = file.name;
  return ossClient.put(fileName, file).then(result => {
    console.log(`Common upload ${file.name} succeeded, result === `, result)
  }).catch(err => {
    console.log(`Common upload ${file.name} failed === `, err);
  });
}

// 分片上传
async function multipartUpload(file) {
  if (!ossClient) {
    await initOSSClient();
  }
  const fileName = file.name;
  return ossClient.multipartUpload(fileName, file, {
    parallel,
    partSize,
    progress: onMultipartUploadProgress
  }).then(result => {
    // 生成文件下载地址
    const url = `http://${bucket}.${region}.aliyuncs.com/${fileName}`;
    console.log(`Multipart upload ${file.name} succeeded, url === `, url, result)
  }).catch(err => {
    console.log(`Multipart upload ${file.name} failed === `, err);
    if (ossClient) {
        // ossClient.cancel();
      }
  });
}
// 断点续传
async function resumeMultipartUpload() {
  Object.values(checkpoints).forEach((checkpoint) => {
    const { uploadId, file, name } = checkpoint;
    ossClient.multipartUpload(uploadId, file, {
      parallel,
      partSize,
      progress: onMultipartUploadProgress,
      checkpoint
    }).then(result => {
      console.log('before delete checkpoints === ', checkpoints);
      delete checkpoints[checkpoint.uploadId];
      console.log('after delete checkpoints === ', checkpoints);
      const url = `http://${bucket}.${region}.aliyuncs.com/${name}`;
      console.log(`Resume multipart upload ${file.name} succeeded, url === `, url)
    }).catch(err => {
      console.log('Resume multipart upload failed === ', err);
    });
  });
}

// 分片上传进度改变回调
async function onMultipartUploadProgress(progress, checkpoint) {
    console.log(checkpoint)
  console.log(`${checkpoint.file.name} 上传进度 ${progress}`);
  checkpoints[checkpoint.uploadId] = checkpoint;
  // 判断STS Token是否将要过期，过期则重新获取
  const { Expiration } = credentials;
  const timegap = 1;
  if (Expiration && moment(Expiration).subtract(timegap, 'minute').isBefore(moment())) {
    console.log(`STS token will expire in ${timegap} minutes，uploading will pause and resume after getting new STS token`);
    if (ossClient) {
      ossClient.cancel();
    }
    await getCredential();
    await resumeMultipartUpload();
  }
}

// 暂停上传
function stop() {
  status.innerText = 'Stopping';
  if (ossClient) ossClient.cancel();
}

// 续传
function resume() {
  status.innerText = 'Resuming';
  if (ossClient) resumeMultipartUpload();
}